"use strict";

var _ = require('underscore'),
    S = require("string"),
    path = require('path'),
    moment = require('moment'),
    C = require('./common.js');

var fileBasedI18nFactory = function (basePath, lang) {
    return function (domain, text, values) {
        var path = basePath + lang + '/' + domain + '.js',
            langInfo, translated;

        try {
            langInfo = require(path);
        } catch (e) {
            C.H.syslog('warn', 'Missing language file: ' + path);
        }

        if (langInfo) {
            translated = langInfo[text];
            if (!translated) {
                C.H.syslog('warn', 'Missing translation: ' + path + ' -> ' + text);
                translated = text;
            }
        } else {
            translated = text;
        }

        return this.values ? S(translated).template(values).s : translated;
    };
};

var nonI18n = function (domain, text, values) {
    return values ? S(text).template(this.values).s : text;
};

exports.create = function (basePath, lang) {
    if (!lang) {
        return nonI18n;
    }

    C.excludeDotDotInPath('language locale', lang.locale);

    lang.storage || (lang.storage = 'lang');

    if (_.isString(lang.storage)) {
        var langPath = path.resolve(basePath, lang.storage);
        langPath = C.ensureRightSlash(langPath);

        return fileBasedI18nFactory(langPath, lang.locale);
    }

    //todo: add other storage factory
    return nonI18n;
};

exports.moment = function (value, lang) {
    var m = moment(value);
    _.isObject(lang) && lang.date && m.lang(lang.date);
    return m;
};


